package com.chenx.myapplicationcom1

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements
import java.io.IOException

class ImageViewModel : ViewModel() {

    private val _images = MutableStateFlow<List<String>>(emptyList())
    val images: StateFlow<List<String>> = _images

    fun fetchImages(url: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val client = OkHttpClient()
                val request = Request.Builder().url(url).build()
                val response = client.newCall(request).execute()
                val html = response.body?.string()

                if (html != null) {
                    val doc: Document = Jsoup.parse(html)
                    val imageElements: Elements = doc.select("img")

                    val imageUrls = imageElements.map { it.attr("src") }
                    _images.value = imageUrls
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }
}
